﻿Ext.ns('suce.solicitud_dgs006.producto');

suce.solicitud_dgs006.producto.edit = function (config) {

    return new Ext.Dialog(Ext.apply({

        title: 'Edición de Producto',
        layout: 'border',
        height: 600,
        width: 600,

        initComponent: function () {
            var me = this,
                form,
                pnlProductos,
                plgEditorC,
                plgEditorA,
                plgEditorE;

            plgEditorC = Ext.create('Ext.grid.plugin.CellEditing', {
                clicksToEdit: 1,
                listeners: {
                    beforeEdit: function () { return !me.readOnly; },
                    edit: function (edt, e) {
                        e.record.commit();
                    }
                }
            });

            plgEditorA = Ext.create('Ext.grid.plugin.CellEditing', {
                clicksToEdit: 1,
                listeners: {
                    beforeEdit: function () { return !me.readOnly; },
                    edit: function (edt, e) {
                        e.record.commit();
                    }
                }
            });

            plgEditorE = Ext.create('Ext.grid.plugin.CellEditing', {
                clicksToEdit: 1,
                listeners: {
                    beforeEdit: function () { return !me.readOnly; },
                    edit: function (edt, e) {
                        e.record.commit();
                    }
                }
            });

            if (me.readOnly === true) {
                me.bbar = ['->',
                    { text: 'Cerrar', handler: me.onEsc, scope: me, iconCls: 'tb-exit' }
                ];
            } else {
                me.bbar = ['->',
                    { text: '<b>Aceptar</b>', itemId: 'btnOk', handler: me.ok, scope: me, iconCls: 'tb-save' },
                    { text: 'Cancelar', handler: me.onEsc, scope: me, iconCls: 'tb-exit' }
                ];
            }

            form = new Ext.form.Panel({
                baseCls: 'x-plain',
                bodyPadding: 10,
                height: 170,
                region: 'north',
                fieldDefaults: { labelWidth: 70, anchor: '-10' },
                items: [
                    HBOX([
                        TEXT('nombproducto', 'Nombre', 2000)
                    ]),
                    HBOX([
                       TEXT('marcproducto', 'Marca', 300)
                    ]),
                    FIELDSET({ title: 'Clasificación' }, [
                        HBOX([
                            CLASIFICACION('idclasificacion', 'Nombre', { anchor: '100%',
                                flex: 2,
                                handler: function (f, v, r) {
                                    if (r) {
                                        me.form.ff('codiclas').setValue(r.data.codiclas);
                                        me.form.ff('codigrupo').setValue(r.data.codigrupo);
                                    } else {
                                        me.form.ff('codiclas').setValue('');
                                        me.form.ff('codigrupo').setValue('');
                                    }
                                }
                            })
                        ]),
                        HBOX([
                            TEXT('codiclas', 'Código', 10, { readOnly: true }),
                            TEXT('codigrupo', 'Grupo', 10, { readOnly: true })
                        ])
                    ])
                ]
            });

            me.gridComp = new Ext.grid.Panel({
                //title: 'Composición',
                region: 'north',
                flex: 1,
                store: SIMPLESTORE([], 'idcomposicion,desccomposicion'),
                columns: COLMODEL([
                    ['desccomposicion', 'Nombre', 0.1, { editor: TEXT('', '', 2000), renderer: function (v, m, r) {
                        return '<div style="white-space:normal">' + v + '</div>';
                    }
                    }]
                ], { sortable: true }),
                plugins: [plgEditorC],
                tbar: [
                    { xtype: 'tbtext', text: '<span style="color:#04468C"><b>Composición</b><span>' }, '->',
                    { text: 'Agregar', handler: Ext.bind(me['new'], me, ['gridComp']), scope: me, iconCls: 'tb-new' },
                    { text: 'Eliminar', handler: Ext.bind(me['delete'], me, ['gridComp']), scope: me, iconCls: 'tb-delete' }
                ]
            });

            me.gridEnv = new Ext.grid.Panel({
                //title: 'Envases',
                region: 'south',
                flex: 1,
                store: SIMPLESTORE([], 'idenvase,tipoenvase,mateenvase,capaenvase'),
                columns: COLMODEL([
                    ['tipoenvase', 'Tipo', 0.1, { editor: TEXT('', '', 50)}],
                    ['mateenvase', 'Material', 0.1, { editor: TEXT('', '', 150), renderer: function (v, m, r) {
                        return '<div style="white-space:normal">' + v + '</div>';
                    }
                    }],
                    ['capaenvase', 'Capacidad', 0.1, { editor: TEXT('', '', 20)}]
                ], { sortable: true }),
                plugins: [plgEditorE],
                tbar: [
                    { xtype: 'tbtext', text: '<span style="color:#04468C"><b>Envases</b><span>' }, '->',
                    { text: 'Agregar', handler: Ext.bind(me['new'], me, ['gridEnv']), scope: me, iconCls: 'tb-new' },
                    { text: 'Eliminar', handler: Ext.bind(me['delete'], me, ['gridEnv']), scope: me, iconCls: 'tb-delete' }
                ]
            });

            me.gridAdi = new Ext.grid.Panel({
                //title: 'Aditivos',
                region: 'center',
                flex: 1,
                store: SIMPLESTORE([], 'idaditivo,descaditivo,pesoaditivo,sincodex,sustgrasa'),
                columns: COLMODEL([
                    ['descaditivo', 'Nombre', 0.1, { editor: TEXT('', '', 250), renderer: function (v, m, r) {
                        return '<div style="white-space:normal">' + v + '</div>';
                    }
                    }],
                    ['sincodex', 'SIN Codex', 50, { editor: TEXT('', '', 50)}],
                    ['pesoaditivo', 'Peso (mg / Kg)', 20, { editor: TEXT('', '', 20)}],
                    ['sustgrasa', 'Sustancia', 20, { editor: TEXT('', '', 20)}]
                ], { sortable: true }),
                plugins: [plgEditorA],
                tbar: [
                    { xtype: 'tbtext', text: '<span style="color:#04468C"><b>Aditivos</b><span>' }, '->',
                    { text: 'Agregar', handler: Ext.bind(me['new'], me, ['gridAdi']), scope: me, iconCls: 'tb-new' },
                    { text: 'Eliminar', handler: Ext.bind(me['delete'], me, ['gridAdi']), scope: me, iconCls: 'tb-delete' }
                ]
            });

            pnlProductos = new Ext.Panel({
                layout: 'border',
                region: 'center',
                border: false,
                items: [
                    form,
                    { border: false, flex: 1, region: 'center', layout: 'border', items: [me.gridComp, me.gridAdi, me.gridEnv] }

                ]
            });

            me.items = [pnlProductos];

            Ext.Dialog.prototype.initComponent.call(me);

            me.form = form.form;
        },

        show: function (p) {
            var me = this;
            p = p || {};
            me.form.reset();
            me.idsolicitud = p.idsolicitud;
            me.idversion = p.idversion;
            me.idproducto = p.idproducto;
            Ext.Dialog.prototype.show.call(me);
            me.reload();
        },

        ok: function () {
            var me = this,
                p = Ext.apply({ C: 'PRODUCTO', S: 'EDIT', idsolicitud: me.idsolicitud, idversion: me.idversion, idproducto: me.idproducto }, me.form.getValues()),
                envase = [],
                aditivo = [],
                composicion = [];

            if (me.form.ff('idclasificacion').getValue() === undefined || me.form.ff('idclasificacion').getValue() === '' || me.form.ff('idclasificacion').getValue() === null) {
                Ext.Msg.message('El producto debe de tener una clasificación');
                return;
            }

            me.gridComp.store.each(function (r) {
                var d = r.data;
                composicion.push([d.idcomposicion, d.desccomposicion].join(']]'));
            });

            p.composicion = composicion.join('<->');

            me.gridEnv.store.each(function (r) {
                var d = r.data;
                envase.push([d.idenvase, d.tipoenvase, d.mateenvase, d.capaenvase].join(']]'));
            });

            p.envase = envase.join('<->');

            me.gridAdi.store.each(function (r) {
                var d = r.data;
                aditivo.push([d.idaditivo, d.descaditivo, d.pesoaditivo, d.sincodex, d.sustgrasa].join(']]'));
            });

            p.aditivo = aditivo.join('<->');

            postServer('solicitud.ashx', p, function () {
                Ext.Msg.message('Datos guardados satisfactoriamente');
                if (me.fireEvent('producto', p) !== false)
                    me.onEsc();
            }, me);
        },

        reload: function () {
            var me = this;
            callServer('solicitud.ashx', { C: 'PRODUCTO', S: 'GETBYID', idsolicitud: me.idsolicitud, idversion: me.idversion, idproducto: me.idproducto }, function (v) {
                v = Ext.decode(v);
                me.form.setValues(v.form);
                me.form.ff('idclasificacion').setRawValue(v.form.nombclasificacion);
                me.gridComp.store.loadData(v.componente);
                me.gridAdi.store.loadData(v.aditivo);
                me.gridEnv.store.loadData(v.envase);
            }, me);
        },


        'new': function (grid) {
            var me = this//,
            //r = GETSELECTED(me[grid]);
            if (me.readOnly === true) return;
            Ext.Msg.confirm('Confirmar', 'Desea agregar un item a la lista ?', function (btn) {
                if (btn == 'yes') {
                    me[grid].store.insert(0, "");
                }
            });
        },

        'delete': function (grid) {
            var me = this,
                r = GETSELECTED(me[grid]);
            if (me.readOnly === true || !r) return;
            Ext.Msg.confirm('Confirmar', 'Seguro de eliminar el item seleccionado?', function (btn) {
                if (btn == 'yes') {
                    me[grid].store.remove(r);
                }
            });
        }


    }, config));
};


suce.solicitud_dgs006.producto.observar = function (config) {

    return new Ext.Dialog(Ext.apply({

        title: 'Observar/Denegar Producto',
        width: 450,
        height: 236,
        layout: 'border',
        modal: true,

        initComponent: function () {
            var me = this,
                form;

            //me.addEvents('update', 'insert');
            //me.addEvents('update');

            me.bbar = ['->',
                { text: '<b>Guardar</b>', handler: me.ok, scope: me, iconCls: 'tb-save' },
                { text: 'Cerrar', handler: me.salir, scope: me, iconCls: 'tb-exit' }
            ];

            form = new Ext.form.Panel({
                region: 'center',
                baseCls: 'x-plain',
                bodyPadding: 8,
                fieldDefaults: { anchor: '-10' },
                items: [
                    LABEL('Texto'),
                    TEXTAREA('descobservacion', '', 4000, { anchor: '100%', value: '', height: '150px' })
                ]
            });

            me.items = [form];
            Ext.Dialog.prototype.initComponent.call(me);
            me.form = form.form;
        },

        show: function (p, e) {
            var me = this;
            Ext.Dialog.prototype.show.call(me);
            me.form.reset();
            //alert(e);
            if (e == 'D')
                me.setTitle('Denegacion del Producto');
            else
                me.setTitle('Observacion del Producto');

            me.form.ff('descobservacion').setValue(p);
        },

        ok: function () {
            var me = this
            if (!ISVALID(me.form)) return;
            functemp(me.form.ff('descobservacion').getValue())
        },

        salir: function () {
            var me = this;
            me.onEsc();
        }

    }, config));
};